//
//  SEGAdDisplayManager.m
//  Commom
//
//  Created by Clavis on 2020/4/29.
//

#import "SEGAdDisplayManager.h"
#import "SEGProfileManager.h"
#import "SEGPlatformManager.h"

@interface SEGAdDisplayManager ()

@property (nonatomic, strong) NSArray<SEGAdDisplayModel *> *adDisplayModelList;

@end

@implementation SEGAdDisplayManager

singleton_m(SEGAdDisplayManager);

- (instancetype)init {
    self = [super init];
    if (self) {
        // 初始化的时候拉取本地数据
        [self getLocalAdDisplayData];
    }
    return self;
}

/// 请求&刷新广告配置
- (void)requestNewConfig {
    
}

// 处理数据
- (NSArray<SEGAdDisplayModel *> *)handleData:(NSDictionary *)result {
    NSMutableArray<SEGAdDisplayModel *> *displayList = [NSMutableArray array];
    if (result[@"data"] && [result[@"data"] isKindOfClass:[NSDictionary class]] && result[@"data"][@"advList"] && [result[@"data"][@"advList"] isKindOfClass:[NSArray class]]) {
        NSArray *advListDic = result[@"data"][@"advList"];
        [advListDic enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SEGAdDisplayModel *subModel = [SEGAdDisplayModel yy_modelWithDictionary:obj];
            [displayList addObject:subModel];
        }];
    }
    return [displayList copy];
}

#pragma mark - 广告配置数据本地缓存
- (void)saveAdDisplayConfig:(NSDictionary *)data {
    // 保存原始数据
    [NSKeyedArchiver archiveRootObject:data toFile:[self adDisplayLocalPath]];
}

/// 获取本地缓存广告展示数据
- (void)getLocalAdDisplayData{
    NSDictionary *localResult = [NSKeyedUnarchiver unarchiveObjectWithFile:[self adDisplayLocalPath]];
    self.adDisplayModelList = [self handleData:localResult];
}

/// 本地广告配置路径
- (NSString*)adDisplayLocalPath{
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    return [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"SEGADDisplay_Archiver_%@.data", kAccountCommunityID]];
}

#pragma mark - data handle

/// 判断广告是否展示
/// @param adType 广告类型
- (BOOL)getAdWhetherShow:(SEGADType)adType {
    /*
     广告展示规则
     1.遍历adDisplayModelList 没有code和adType一致，则不展示
     2.根据对应的AdDisplayModel判断，advertTimeList数组为空或不存在则直接展示
     3.advertTimeList不为空，则根据屏蔽开启结束时间判断，当前时间不在范围内则展示
     */
    
    __block SEGAdDisplayModel *targetModel = nil;
    __block BOOL adShow = NO;
    [self.adDisplayModelList enumerateObjectsUsingBlock:^(SEGAdDisplayModel * _Nonnull displayModel, NSUInteger idx, BOOL * _Nonnull stop) {
        if (displayModel.code == (NSInteger)adType) {
            targetModel = displayModel;
            adShow = YES;
            *stop = YES;
        }
    }];
    
    if (targetModel && targetModel.advertTimeList.count > 0) {
        // 获取当前时间
        NSDate *currentData = [NSDate date];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
        [calendar setTimeZone: timeZone];
        NSCalendarUnit calendarUnit = NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute;
        NSDateComponents *currentComponents = [calendar components:calendarUnit fromDate:currentData];
        NSInteger currentWeek = currentComponents.weekday - 1;
        NSInteger currentHour = currentComponents.hour;
        NSInteger currentMinute = currentComponents.minute;
        NSInteger currentTotalMinute = currentComponents.hour * 60 + currentComponents.minute;
        NSLog(@"%ld %ld %ld", currentWeek, currentHour, currentMinute);
        
        
        if (currentWeek == 0) { //周天特殊处理
            currentWeek = 7;
        }
        
        NSString *dateFormat = @"HH:mm";
        [targetModel.advertTimeList enumerateObjectsUsingBlock:^(SEGAdDisplayTimeModel * _Nonnull displayTimeModel, NSUInteger idx, BOOL * _Nonnull stop) {
            // 星期相同才判断
            if (currentWeek == displayTimeModel.week) {
                NSDate *beginTime = [NSDate dateWithString:ValueToString(displayTimeModel.beginTime) format:dateFormat];
                NSDate *endTime = [NSDate dateWithString:ValueToString(displayTimeModel.endTime) format:dateFormat];
                NSDateComponents *beginTimeComponents = [calendar components:calendarUnit fromDate:beginTime];
                NSDateComponents *endTimeComponents = [calendar components:calendarUnit fromDate:endTime];
                NSInteger beginTimeTotalMinute = beginTimeComponents.hour * 60 + beginTimeComponents.minute;
                NSInteger endTimeTotalMinute = endTimeComponents.hour * 60 + endTimeComponents.minute;
                
                if (currentTotalMinute >= beginTimeTotalMinute && currentTotalMinute <= endTimeTotalMinute) {
                    adShow = NO;
                    *stop = YES;
                }
            }
        }];
    }
    
    return adShow;
}

/// 获取循环展示的广告配置模型（PGC列表，PGC推荐列表，邻里圈列表，话题列表）
/// @param adType 广告类型
- (SEGAdDisplayModel *)getLoopAdDisplayModel:(SEGADType)adType {
    // 广告配置不存在该类型或者不符合展示时间则直接不展示
    if (![self getAdWhetherShow:adType]) {
        return nil;
    }
    
    // 遍历拿到对应广告配置模型
    __block SEGAdDisplayModel *targetModel = nil;
    [self.adDisplayModelList enumerateObjectsUsingBlock:^(SEGAdDisplayModel * _Nonnull displayModel, NSUInteger idx, BOOL * _Nonnull stop) {
       if (displayModel.code == (NSInteger)adType) {
           targetModel = displayModel;
           *stop = YES;
       }
    }];
    // 异常处理
    if (targetModel.showAdvCount <= 0 || targetModel.groupCount <= 0 || targetModel.showAdvCount > targetModel.groupCount) {
        targetModel = nil;
    }
    return targetModel;
}

@end
